package com.ay.weixin.autoreply.domain;

import java.sql.SQLException;

import org.lizar.config.keys.Keys;
import org.lizar.ioc.Container;
import org.lizar.ioc.module.Module;
import org.lizar.json.JObject;
import org.lizar.json.util.JSONParser;
import org.lizar.util.https.Https;

import com.ay.weixin.autoreply.db.IbatisAcessTokenDao;
import com.ay.weixin.config.ProjectConfig;
public class AccessTokenModule extends Module {

	private IbatisAcessTokenDao token_dao;
	
	@Override
	public void init_property() throws Exception {
		token_dao=Container.get(IbatisAcessTokenDao.class);
		
		
	}

	@Override
	public void init_component() throws Exception {
		
	}

	public String getAccessToken(long wxproject_id){
		AccessToken token=null;
		
		try {
			token=token_dao.getLatest(wxproject_id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		if(token==null||token.getExpired_timestamp()<=(System.currentTimeMillis()/1000+600)){
			
			AccessToken new_token=null;
			
			try {
				new_token=fetchToken(wxproject_id);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			
			if(new_token==null){
				return null;
			}
			
			try {
				token_dao.delete(wxproject_id);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				token_dao.insert(new_token);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			
			
			return new_token.getToken();
		}else{
			return token.getToken();
		}
		
	}
	
	public static AccessToken fetchToken(long wxproject_id) throws Exception{
		String url=Keys.getStr("AcessTokenUrl");
		url=String.format(url, ProjectConfig.getStr(wxproject_id,"sys.AppId"),ProjectConfig.getStr(wxproject_id,"sys.AppSecret"));
		JObject jo=null;
		  try { 
			String result=Https.GetMethod(url);
		    jo=(JObject)JSONParser.parse(result); 
		  } catch(Exception e){
			  e.printStackTrace();
		  }
		  
		if(jo==null||jo.getStr("access_token")==null){
			return null;
		}
		AccessToken token=new AccessToken();
		token.setToken(jo.getStr("access_token"));
		token.setExpired_timestamp((System.currentTimeMillis()/1000+jo.getInt("expires_in")));
		token.setInsert_time(System.currentTimeMillis());
		token.setWxproject_id(wxproject_id);
        return token;
	}
	
	
	
	
}
